﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Runtime.Serialization;


public static class Serializer
{
    private static readonly XmlWriterSettings _xmlSettings = new XmlWriterSettings
    {
        OmitXmlDeclaration = true,
        Indent = true,
        NamespaceHandling=System.Xml.NamespaceHandling.OmitDuplicates
    };
    private static readonly XmlReaderSettings _xmlRSettings = new XmlReaderSettings { };

    public static string Serialize<T>(this T source)
    {
        var s = new DataContractSerializer(typeof(T));
        
        if (source == null) return "";
        var sb = new StringBuilder();
        using (var sw = new System.IO.StringWriter(sb))
        {
            using (var xw = XmlTextWriter.Create(sw, _xmlSettings))
            {
                using (var writer =new XmlDictionaryWriterWrapper(XmlDictionaryWriter.CreateDictionaryWriter(xw)))
                    s.WriteObject(writer, source);
            }
        }
        return sb.ToString();
    }
    public static string Serialize<T>(this T source, string typeName)
    {
        var t = Type.GetType(typeName);
        var s = new DataContractSerializer(t);
        
        if (source == null) return "";
        var sb = new StringBuilder();
        using (var sw = new System.IO.StringWriter(sb))
        {
            using (var xw = XmlTextWriter.Create(sw, _xmlSettings))
            {
                using (var writer = new XmlDictionaryWriterWrapper(XmlDictionaryWriter.CreateDictionaryWriter(xw)))
                    s.WriteObject(writer, source);
            }
        }
        return sb.ToString();
    }


    public static object Deserialize(this string source, string typeName)
    {
        var t = Type.GetType(typeName);
        var s = new DataContractSerializer(t);
        
        if (string.IsNullOrEmpty(source)) return null;
        using (var sr = new System.IO.StringReader(source))
        {
            using (var xr = XmlReader.Create(sr))
            {
                using (var r = XmlDictionaryReader.CreateDictionaryReader((xr)))
                {
                    return s.ReadObject(xr, false);
                }
            }
        }
    }

    public static  T Deserialize<T>(this string source)
    {   
        var s = new DataContractSerializer(typeof(T));
        T result = default(T);
        if (string.IsNullOrEmpty(source)) return result;
        using (var sr = new System.IO.StringReader(source))
        {
            using (var xr = XmlReader.Create(sr))
            {
                using (var r = XmlDictionaryReader.CreateDictionaryReader((xr)))
                {
                    result = (T)s.ReadObject(xr, false);
                }
            }
        }
        return result;
    }
}
